#include "./lab1Utils.cpp"

char my_getchar()
{
    char c;
    cin >> c;
    return c;
}
const int time_slice = 3; // 一个时间片，用于模拟执行到中间被阻塞
const int MAX_PROCESS_NUM = 5;

// 模拟进程状态转换
int main()
{
    PCBList *ready = new PCBList("就绪");
    PCBList *block_ready = new PCBList("阻塞就绪"); // 阻塞完毕的进程，优先于普通的就绪队列
    PCBList *block = new BlockList("阻塞", block_ready);
    PCBList *end = new PCBList("结束");

    for (int i = 0; i < MAX_PROCESS_NUM; i++)
    {
        ready->insert(create_pcb("P" + to_string(i)));
    }

    while (!ready->empty() || !block_ready->empty())
    {
        PCB *first_in_list;
        if (!block_ready->empty())
        {
            first_in_list = block_ready->get(0);
            block_ready->remove(0);
        }
        else
        {
            first_in_list = ready->get(0);
            ready->remove(0);
        }

        cout << "当前执行进程为:" << first_in_list->process_name << " 剩余时间: " << first_in_list->remaining_time << endl;

        bool is_block = false;
        // 三次循环是一个时间片循环是为了模拟一个时间片执行的过程
        for (int i = 0; i < time_slice; i++)
        {
            cout << "是否阻塞? Y/N" << endl;
            if (my_getchar() == 'Y')
            {
                cout << "输入阻塞时间和原因";
                cin >> first_in_list->wait_time >> first_in_list->wait_reason;
                block->update_list();
                block->insert(first_in_list);
                is_block = true;
                cout << endl;
                break;
            }
        }
        if (is_block)
            continue;
        first_in_list->priority--;
        first_in_list->remaining_time--;
        if (first_in_list->remaining_time == 0)
        {
            end->insert(first_in_list);
        }
        else
        {
            ready->insert(first_in_list);
        }
        block->update_list();
        ready->print();
        block_ready->print();
        block->print();
        end->print();
        cout << endl;
    }
    return 0;
}
